var stationHistory = require('../models/stationHistory');
var Station = require('../models/station');
var LabelInfo = require('../models/label');
var labelHistory = require('../models/labelHistory');

var fs = require("fs");
var path = require("path");
var child_process = require('child_process');

var stationHistoryInfo = [];
var labelHistoryInfo = [];
var stationNum = 0;
var stationLastOne = 0;
var labelNum = 0;
var labelLastOne = 0;

var allDataObj = {};
var lastDataArr = [];


var elasticsearch = require('elasticsearch');
var client = new elasticsearch.Client({
    host: '192.168.1.17:9200'
    // log: 'trace'
});

function getHistoryInfo(start, end, fileName) {
    client.search({
        index: 'bigship',
        type: 'history',
        body: {
            query: {
                range: {timestamp: {gte: start, lte: end}}
            }, size: 10000
        }
    }).then(function (resp) {
        var data = resp.hits.hits;
        var allDataObj = {};
        for (var j = 0; j < data.length; j++) {
            if (!allDataObj.hasOwnProperty(data[j]._source.eventName)) {
                allDataObj[data[j]._source.eventName] = [];
            }
        }
        for (var i = 0; i < data.length; i++) {
            allDataObj[data[i]._source.eventName].push(data[i]._source)
        }

        getTimeDifference(start, end, allDataObj, fileName)
    }, function (err) {
        console.trace(err.message);
    });
}


function getTimeStamp(time1, time2, timeDifference) {
    var files = fs.readdirSync('./data/result');
    // console.log(files)
    for (var i = 0; i < files.length; i++) {
        var filePath = './data/result/' + files[i];
        // 在这里添加下边的方法
        var fileNameArr = files[i].split('.');
        fileNameArr.shift();
        var fileName = fileNameArr.join('.');
        allDataObj[fileName] = [];

        var data = fs.readFileSync(filePath);
        var line = data.toString().split('\n');
        for (var j = 0; j < line.length; j++) {
            if (line[j] != '') {
                var dataLine = JSON.parse(line[j]);
                timeArr.push(dataLine.timestamp);
                allDataObj[fileName].push(dataLine)
            }
        }
    }
    // console.log(allDataObj); //从这里开始获取总体时间差。
    getLastData(time1, time2, timeDifference, allDataObj)
}


function getTime(timeStamp) {
    return parseInt(timeStamp / 1000)
}


function getTimeDifference(start, end, allDataObj, fileName) {
    var startTime = getTime(start);
    var endTime = getTime(end);
    var timeDifference = endTime - startTime;
    console.log(timeDifference);
    getLastData(startTime, endTime, timeDifference, allDataObj, fileName)
}


function getLastData(startTime, endTime, timeDifference, allDataObj, fileName) {
    console.log('=====================time');
    if (Object.keys(allDataObj).length == 0) {
        return fs.writeFileSync('data/' + fileName, '[]');
    }
    for (var i = 0; i < timeDifference; i++) {
        var obj = {};
        for (var j in allDataObj) {
            if (j in obj == true) {
                getOneSecondData(obj,j,i,startTime,endTime,allDataObj);
            } else {
                obj[j] = [];
                getOneSecondData(obj,j,i,startTime,endTime,allDataObj);
            }
        }
        lastDataArr.push(obj);
    }
    saveDataArr(fileName);
    // console.log(lastDataArr[0]);   // 这里得到基本的数据。（不包含节点信息的数据。）
}

function getOneSecondData(obj,name,i,startTime,endTime,allDataObj) {
    for (var z = 0; z < allDataObj[name].length; z++) {
        var timeData = getTime(allDataObj[name][z].timestamp);
        if (startTime + i <= timeData && timeData < startTime + i + 1 && startTime <= timeData && timeData <= endTime) {
            obj.timestamp = allDataObj[name][z].timestamp;
            obj[name].push(allDataObj[name][z])
        }
    }
}

function saveDataArr(fileName) {
    fs.writeFile('data/' + fileName, JSON.stringify(lastDataArr), function (err) {
        // res.sendFile(path.join(__dirname, '../data/result.txt'))
        console.log('--保存文件结束！！！')
    });
    lastDataArr.length = 0;
}

// function getLastData(time1, time2, timeDifference, allDataObj) {
//     console.log('=====================time');
//     // console.log(time1)
//     // console.log(time2)
//     for(var i=0;i<timeDifference;i++){
//         var obj = {};
//         obj.data = {};
//         obj.eulerAngle = {};
//         obj.status = [];
//
//         for(var j in allDataObj){
//             var nodeID = j.split('.')[0];
//             var name = j.split('.')[1];
//
//             if(nodeID != 'global'){
//                 if(nodeID in obj.data == true && name in obj.data[nodeID] == true){
//                     for(var z=0;z<allDataObj[j].length;z++){
//                         var timeData = getTime(allDataObj[j][z].timestamp);
//                         if(time1 + i <= timeData && timeData < time1 + i + 1 && time1 <= timeData && timeData <= time2){
//                             obj.timestamp = allDataObj[j][z].timestamp;
//                             obj.data[nodeID][name].push(allDataObj[j][z])
//                         }
//                     }
//                 }if(nodeID in obj.data == true && name in obj.data[nodeID] == false){
//                     obj.data[nodeID][name] = [];
//                     for(var z=0;z<allDataObj[j].length;z++){
//
//                         var timeData = getTime(allDataObj[j][z].timestamp);
//                         if(time1 + i <= timeData && timeData < time1 + i + 1 && time1 <= timeData && timeData <= time2){
//                             obj.timestamp = allDataObj[j][z].timestamp;
//                             obj.data[nodeID][name].push(allDataObj[j][z])
//                         }
//                     }
//                 }if(nodeID in obj.data == false){
//                     obj.data[nodeID] = {};
//                     obj.data[nodeID][name] = [];
//                     for(var z=0;z<allDataObj[j].length;z++){
//
//                         var timeData = getTime(allDataObj[j][z].timestamp);
//                         if(time1 + i <= timeData && timeData < time1 + i + 1 && time1 <= timeData && timeData <= time2){
//                             obj.timestamp = allDataObj[j][z].timestamp;
//                             obj.data[nodeID][name].push(allDataObj[j][z])
//                         }
//                     }
//                 }
//             }else if(nodeID == 'global' && name != 'status'){
//                 if(nodeID in obj.eulerAngle == true && name in obj.eulerAngle[nodeID] == true){
//                     for(var a=0;a<allDataObj[j].length;a++){
//
//                         var timeEulerAngle = getTime(allDataObj[j][a].timestamp);
//                         if(time1 + i <= timeEulerAngle && timeEulerAngle < time1 + i + 1 && time1 <= timeEulerAngle && timeEulerAngle <= time2){
//                             obj.timestamp = allDataObj[j][a].timestamp;
//                             obj.eulerAngle[nodeID][name].push(allDataObj[j][a])
//                         }
//                     }
//                 }if(nodeID in obj.eulerAngle == true && name in obj.eulerAngle[nodeID] == false){
//                     obj.eulerAngle[nodeID][name] = [];
//                     for(var a=0;a<allDataObj[j].length;a++){
//
//                         var timeEulerAngle = getTime(allDataObj[j][a].timestamp);
//                         if(time1 + i <= timeEulerAngle && timeEulerAngle < time1 + i + 1 && time1 <= timeEulerAngle && timeEulerAngle <= time2){
//                             obj.timestamp = allDataObj[j][a].timestamp;
//                             obj.eulerAngle[nodeID][name].push(allDataObj[j][a])
//                         }
//                     }
//                 }if(nodeID in obj.eulerAngle == false){
//                     obj.eulerAngle[nodeID] = {};
//                     obj.eulerAngle[nodeID][name] = [];
//                     for(var a=0;a<allDataObj[j].length;a++){
//
//                         var timeEulerAngle = getTime(allDataObj[j][a].timestamp);
//                         if(time1 + i <= timeEulerAngle && timeEulerAngle < time1 + i + 1 && time1 <= timeEulerAngle && timeEulerAngle <= time2){
//                             obj.timestamp = allDataObj[j][a].timestamp;
//                             obj.eulerAngle[nodeID][name].push(allDataObj[j][a])
//                         }
//                     }
//                 }
//             }else {
//                 for(var b=0;b<allDataObj[j].length;b++){
//                     var timeStatus = getTime(allDataObj[j][b].timestamp);
//                     if(time1 + i <= timeStatus && timeStatus < time1 + i + 1 && time1 <= timeStatus && timeStatus <= time2){
//                         obj.timestamp = allDataObj[j][b].timestamp;
//                         obj.status.push(allDataObj[j][b])
//                     }
//                 }
//             }
//         }
//         lastDataArr.push(obj);  // 这里得到基本的数据。（不包含节点信息的数据。）
//     }
//     // console.log(lastDataArr);   //这个方法用于展示历史数据和历史节点的更新
//
// }

function createStationInfo(allId, result) {
    var arr = [];
    for (var j = 0; j < result.length; j++) {
        if (result[j].id === allId[stationNum]) {
            arr.push(result[j])
        }
    }

    stationHistoryInfo.push(arr);
    stationNum++;
    if (stationNum < allId.length) {
        createStationInfo(allId, result)
    }
}

function getStationHistory(data, req, res) {
    stationHistory.findByDate(req.query.startTime, req.query.endTime).then(function (result) {
        var allId = [];
        for (var i = 0; i < result.length; i++) {
            if (allId.indexOf(result[i].id) === -1) {
                allId.push(result[i].id)
            }
        }

        for (var j = 0; j < data.length; j++) {
            if (allId.indexOf(data[j].id) === -1) {
                allId.push(data[j].id)
            }
        }

        createStationInfo(allId, result);
        stationHistoryData(allId, req, res)
    }, function (error) {
        res.send({status: false, message: error})
    });
}

function stationHistoryData(data, req, res) {
    if (stationHistoryInfo[stationLastOne] && stationHistoryInfo[stationLastOne].length == 0) {
        getOneData(data, req, res)
    } else if (stationLastOne <= stationHistoryInfo.length - 1) {
        stationLastOne++;
        stationHistoryData(data, req, res)
    } else {
        console.log('---------------send');
        res.send({
            stationHistoryInfo: stationHistoryInfo
        });
        console.log('--返回station结束！！！')
    }
}

function getOneData(data, req, res) {
    stationHistory.getLastData(req.query.startTime, data[stationLastOne]).then(function (result) {
        if (result && !result.hasOwnProperty('delete')) {
            stationHistoryInfo[stationLastOne].push(result);
        }
        stationLastOne++;
        stationHistoryData(data, req, res)
    }, function (error) {
        res.send({status: false, message: error})
    })
}

function createLabelInfo(allId, result) {
    var arr = [];
    for (var j = 0; j < result.length; j++) {
        if (result[j].id === allId[labelNum]) {
            arr.push(result[j])
        }
    }

    labelHistoryInfo.push(arr);
    labelNum++;
    if (labelNum < allId.length) {
        createLabelInfo(allId, result)
    }
}

function getLabelHistory(data, req, res) {
    labelHistory.findByDate(req.query.startTime, req.query.endTime).then(function (result) {
        var allId = [];
        for (var i = 0; i < result.length; i++) {
            if (allId.indexOf(result[i].id) === -1) {
                allId.push(result[i].id)
            }
        }

        for (var j = 0; j < data.length; j++) {
            if (allId.indexOf(data[j].id) === -1) {
                allId.push(data[j].id)
            }
        }

        createLabelInfo(allId, result);
        labelHistoryData(allId, req, res)
    }, function (error) {
        res.send({status: false, message: error})
    });
}

function labelHistoryData(data, req, res) {
    if (labelHistoryInfo[labelLastOne] && labelHistoryInfo[labelLastOne].length == 0) {
        getOneLabelData(data, req, res)
    } else if (labelLastOne <= labelHistoryInfo.length - 1) {
        labelLastOne++;
        labelHistoryData(data, req, res)
    } else {
        res.send({
            labelHistoryInfo: labelHistoryInfo
        });
        console.log('--返回label结束！！！')
    }
}

function getOneLabelData(data, req, res) {
    labelHistory.getLastData(req.query.startTime, data[labelLastOne]).then(function (result) {
        if (result && !result.hasOwnProperty('delete')) {
            console.log('-------lastOne----');
            stationHistoryInfo[stationLastOne].push(result);
        }
        labelLastOne++;
        labelHistoryData(data, req, res)
    }, function (error) {
        res.send({status: false, message: error})
    })
}

module.exports = {

    createHistoryData: function (req, res) {
        var timeDifference = getTime(req.query.endTime) - getTime(req.query.startTime);
        console.log(timeDifference);
        var fileName = new Date().getTime() + '.json';
        try {
            getHistoryInfo(req.query.startTime, req.query.endTime, fileName);
            res.send({status: true, fileName: fileName})
        } catch (err) {
            getHistoryInfo(req.query.startTime, req.query.endTime, fileName);
            res.send({status: true, fileName: fileName})
        }
        // 1507882700205,1507882899205
    },
    getHistoryDataFile: function (req, res) {
        fs.exists(path.join(__dirname, '../data/' + req.query.fileName), function (exists) {
            console.log(path.join(__dirname, '../data/' + req.query.fileName))
            console.log("文件是否存在:" + exists);
            if (exists) {
                res.sendFile(path.join(__dirname, '../data/' + req.query.fileName))
            } else {
                res.send(false)
            }
        });
    },
    getAllHistoryInfo: function (req, res) {
        res.send({
            label: [[{
                "nodeID": 1,
                "beforeUpdateInfo": null,
                "afterUpdateInfo": {
                    "name": 1, "type": "UWB",
                    "nodeID": 1
                },
                "updateDate": 1507882790205
            }],
                [{
                    "nodeID": 2,
                    "beforeUpdateInfo": null,
                    "afterUpdateInfo": {
                        "name": 2, "type": "UWB", "nodeID": 2
                    },
                    "updateDate": 1507882700205
                }, {
                    "nodeID": 2,
                    "beforeUpdateInfo": {
                        "name": 2, "type": "UWB", "nodeID": 2
                    },
                    "afterUpdateInfo": {
                        "name": 21, "type": "UWB", "nodeID": 2
                    },
                    "updateDate": 1507882899205
                }, {
                    "nodeID": 2,
                    "beforeUpdateInfo": {
                        "name": 21, "type": "UWB", "nodeID": 2
                    },
                    "afterUpdateInfo": {
                        "name": 22, "type": "UWB", "nodeID": 2
                    },
                    "updateDate": 1507882999205
                }]
                , [{
                    "nodeID": 3,
                    "beforeUpdateInfo": null,
                    "afterUpdateInfo": {
                        "name": 3, "type": "UWB", "nodeID": 3
                    },
                    "updateDate": 1507882700205
                }, {
                    "nodeID": 3,
                    "beforeUpdateInfo": null,
                    "afterUpdateInfo": {
                        "name": 31, "type": "UWB", "nodeID": 3
                    },
                    "updateDate": 1507882899205
                }]],
            station: [[{
                "nodeID": 4,
                "beforeUpdateInfo": null,
                "afterUpdateInfo": {
                    "name": 4, "type": "UWB", "z": 999, "y": 999, "x": 999,
                    "nodeID": 4
                },
                "updateDate": 1507882790205
            }],
                [{
                    "nodeID": 5,
                    "beforeUpdateInfo": null,
                    "afterUpdateInfo": {
                        "name": 5, "type": "UWB", "nodeID": 5, "z": 0, "y": 0, "x": 0
                    },
                    "updateDate": 1507882700205
                }, {
                    "nodeID": 5,
                    "beforeUpdateInfo": {
                        "name": 5, "type": "UWB", "nodeID": 5, "z": 0, "y": 0, "x": 0
                    },
                    "afterUpdateInfo": {
                        "name": 51, "type": "UWB", "nodeID": 5, "z": 1, "y": 1, "x": 1
                    },
                    "updateDate": 1507882899205
                }, {
                    "nodeID": 5,
                    "beforeUpdateInfo": {
                        "name": 51, "type": "UWB", "nodeID": 5, "z": 1, "y": 1, "x": 1
                    },
                    "afterUpdateInfo": {
                        "name": 52, "type": "UWB", "nodeID": 5, "z": 2, "y": 2, "x": 2
                    },
                    "updateDate": 1507882999205
                }]]
        })
    },
    getLabelHistoryInfo: function (req, res) {
        labelNum = 0;
        labelLastOne = 0;
        labelHistoryInfo = [];
        LabelInfo.all().then(function (label) {
            if (label != 0) {
                getLabelHistory(label, req, res)
            } else {
                res.send({
                    labelHistoryInfo: labelHistoryInfo
                })
            }
        }, function (error) {
            res.send({status: 400, message: error})
        });
    },
    getStationHistoryInfo: function (req, res) {
        stationNum = 0;
        stationLastOne = 0;
        stationHistoryInfo = [];
        Station.all().then(function (stations) {
            if (stations != 0) {
                getStationHistory(stations, req, res)
            } else {
                res.send({
                    stationHistoryInfo: stationHistoryInfo
                })
            }
        }, function (error) {
            res.send({status: 400, message: error})
        });
    }
    // var stationInfo = []
        // var labelInfo = []
        // for (var j = 0; j < 1000; j++) {
        //     labelInfo.push([{
        //         nodeID: '1',
        //         name: '王小虎',
        //         type: '人',
        //         status: Math.random().toFixed(2) > 0.2 ? '正常' : '低电',
        //         coordinate: Math.random().toFixed(2) + ',' + Math.random().toFixed(2) + ',' + Math.random().toFixed(2)
        //     }, {
        //         nodeID: '2',
        //         name: '唐一白',
        //         type: '人',
        //         status: Math.random().toFixed(2) > 0.2 ? '正常' : '低电',
        //         coordinate: Math.random().toFixed(2) + ',' + Math.random().toFixed(2) + ',' + Math.random().toFixed(2)
        //     }, {
        //         nodeID: '3',
        //         name: '班小松',
        //         type: '机',
        //         status: Math.random().toFixed(2) > 0.2 ? '正常' : '低电',
        //         coordinate: Math.random().toFixed(2) + ',' + Math.random().toFixed(2) + ',' + Math.random().toFixed(2)
        //     }, {
        //         nodeID: '4',
        //         name: '云朵',
        //         type: '机',
        //         status: Math.random().toFixed(2) > 0.2 ? '正常' : '低电',
        //         coordinate: Math.random().toFixed(2) + ',' + Math.random().toFixed(2) + ',' + Math.random().toFixed(2)
        //     }])
        // }
        // for (var i = 0; i < 1000; i++) {
        //     stationInfo.push([{
        //         nodeID: '1',
        //         name: '机库顶',
        //         type: 'UWB',
        //         status: Math.random().toFixed(2) > 0.2 ? '正常' : '低电',
        //         coordinate: Math.random().toFixed(2) + ',' + Math.random().toFixed(2) + ',' + Math.random().toFixed(2)
        //     }, {
        //         nodeID: '2',
        //         name: '船头',
        //         type: 'GPS',
        //         status: Math.random().toFixed(2) > 0.2 ? '正常' : '低电',
        //         coordinate: Math.random().toFixed(2) + ',' + Math.random().toFixed(2) + ',' + Math.random().toFixed(2)
        //     }, {
        //         nodeID: '3',
        //         name: '机库顶',
        //         type: 'GPS',
        //         status: Math.random().toFixed(2) > 0.2 ? '正常' : '低电',
        //         coordinate: Math.random().toFixed(2) + ',' + Math.random().toFixed(2) + ',' + Math.random().toFixed(2)
        //     }, {
        //         nodeID: '4',
        //         name: '船尾',
        //         type: 'UWB',
        //         status: Math.random().toFixed(2) > 0.2 ? '正常' : '低电',
        //         coordinate: Math.random().toFixed(2) + ',' + Math.random().toFixed(2) + ',' + Math.random().toFixed(2)
        //     }])
        // }
        // var angleList = []
        // for (var o = 0; o < 1000; o++) {
        //     angleList.push({
        //         'firstangle': (Math.PI * Math.random()).toFixed(2),
        //         'secondangle': (Math.PI * Math.random()).toFixed(2),
        //         'thirdangle': (Math.PI * Math.random()).toFixed(2)
        //     })
        // }
        // var blockLocomotion = []
        // for (var n = 0; n < 1000; n++) {
        //     blockLocomotion.push({
        //         'historyFirstRegion': {'小明': [Math.random() * 90, Math.random() * 180], '小红': [Math.random() * 90, Math.random() * 180]},
        //         'historySecondRegion': {
        //             '小明': [Math.random() * 90, Math.random() * 180],
        //             '小红': [Math.random() * 90, Math.random() * 180],
        //             '小花': [Math.random() * 90, Math.random() * 180]
        //         }
        //     })
        // }
        //
        // console.log(req.body);
        // res.send({
        //     blockLocomotion:blockLocomotion,
        //     angleList:angleList,
        //     labelInfo:labelInfo,
        //     stationInfo: stationInfo
        // })
};